<template>
  <div>
    <!-- 页面头部，显示页面标题 -->
    <Header title="用户管理"></Header>

    <!-- 搜索栏区域：提供用户搜索功能 -->
    <div class="search-bar">
      <!-- 根据用户名搜索 -->
      <el-input  :prefix-icon="Search" v-model="searchKeyword" placeholder="根据用户名搜索" clearable @input="searchUser" />
      <!-- 根据手机号搜索 -->
      <el-input :prefix-icon="Search" v-model="searchPhone" placeholder="根据手机号搜索" clearable @input="searchUser" />
      <!-- 筛选用户状态 -->
      <!-- <el-select v-model="statusFilter" placeholder="筛选用户状态">
        <el-option label="全部" value="" />
        <el-option label="正常" value="1" />
        <el-option label="禁用" value="0" />
      </el-select> -->
    </div>

    <!-- 用户列表表格设置一下表头背景色 -->
    <el-table :data="paginatedUsers" border stripe style="width: 100%" :header-cell-style="{background:'#CFCFCFFF',color:'#000000'}">
      <!-- 用户id -->
      <el-table-column prop="id" label="用户id" />
      <!-- 用户名列 -->
      <el-table-column prop="userName" label="用户名" />
      <!-- 账号列 -->
      <el-table-column prop="userAccount" label="账号" />
      <!-- 头像列 -->
      <el-table-column prop="avatar" label="头像">
        <template #default="scope">
          <!-- 显示用户头像 -->
          <img :src="scope.row.avatar" alt="Avatar" style="width: 30px; height: 30px; border-radius: 50%" />
        </template>
      </el-table-column>
      <!-- 手机号列 -->
      <el-table-column prop="phone" label="手机号">
        <template #default="scope">
          <span v-if="scope.row.phone">{{ scope.row.phone }}</span>
          <span v-else>暂未绑定</span>
        </template>
      </el-table-column>
      <!-- 状态列 -->
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <!-- 用户状态开关 -->
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="updateUserStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <!-- 性别列 -->
      <el-table-column prop="gender" label="性别">
        <template #default="scope">
          <!-- 显示用户性别 -->
          {{ scope.row.gender }}
        </template>
      </el-table-column>
      <!-- 注册时间 -->
      <el-table-column prop="createTime" label="注册时间" />

      <!-- 操作列 -->
      <el-table-column label="操作">
        <template #default="scope">
          <!-- 编辑按钮 -->
          <el-button type="primary"  icon="Edit" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <!-- 删除按钮 -->
          <el-button type="danger"  icon="Delete" size="small" @click="openDeleteConfirm(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="totalUsers"
      />
    </div>

    <!-- 编辑用户信息弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户信息">
      <!-- 显示用户头像 -->
      <div style="text-align: center; margin-bottom: 10px;">
        <img :src="editUser.avatar" alt="Avatar" style="width: 80px; height: 80px; border-radius: 50%" />
      </div>
      <!-- 编辑表单 -->
      <el-form :model="editUser" label-width="80px">
        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input v-model="editUser.userName" />
        </el-form-item>
        <!-- 账号 -->
        <el-form-item label="账号">
          <el-input v-model="editUser.userAccount" />
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item label="手机号">
          <el-input v-model="editUser.phone" />
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码">
          <el-input v-model="editUser.password" type="password" />
        </el-form-item>
        <!-- 性别 -->
        <el-form-item label="性别">
          <el-radio v-model="editUser.gender" label="男">男</el-radio>
          <el-radio v-model="editUser.gender" label="女">女</el-radio>
        </el-form-item>
        <!-- 保存和取消按钮 -->
        <el-form-item>
          <el-button type="primary" @click="saveEditUser">保存</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { getUserListApi, updateUserInfoApi, deleteUserByIdApi } from '@/apis/userManageApi';
import Header from '@/views/ui/header.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Calendar, Search } from '@element-plus/icons-vue'
// 用户数据列表
const users = ref([]);
// 用户名搜索关键词
const searchKeyword = ref('');
// 手机号搜索关键词
const searchPhone = ref('');
// 用户状态筛选条件
const statusFilter = ref('');
// 当前分页页码
const currentPage = ref(1);
// 每页显示数量
const pageSize = ref(10);
// 用户总数
const totalUsers = ref(0);
// 分页后显示的用户数据
const paginatedUsers = ref([]);
// 编辑用户弹窗是否显示
const editDialogVisible = ref(false);
// 当前编辑的用户数据
const editUser = ref({});
// 待删除用户的 ID
const deleteUserId = ref(null);

/**
 * 获取用户列表数据
 */
const fetchUserList = async () => {
  try {
    const res = await getUserListApi();
    users.value = res.data;
    totalUsers.value = users.value.length;
    applyFiltersAndPagination();
  } catch (error) {
    console.error('获取用户列表失败:', error);
  }
};

/**
 * 根据搜索条件筛选用户
 */
const searchUser = () => {
  applyFiltersAndPagination();
};

/**
 * 根据用户状态筛选用户
 * @param user 当前用户数据
 * @returns {boolean} 是否匹配筛选条件
 */
const filterByStatus = (user) => {
  if (statusFilter.value === '') return true;
  return user.status.toString() === statusFilter.value;
};

/**
 * 应用筛选和分页逻辑
 */
const applyFiltersAndPagination = () => {
  let filteredUsers = users.value.filter(user => {
    let nameMatch = false;
    if (user.userName) {
      nameMatch = user.userName.toLowerCase().includes(searchKeyword.value.toLowerCase());
    }
    let phoneMatch = false;
    if (user.phone) {
      phoneMatch = user.phone.includes(searchPhone.value);
    }
    const statusMatch = filterByStatus(user);
    return (nameMatch || !searchKeyword.value) && (phoneMatch || !searchPhone.value) && statusMatch;
  });
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  paginatedUsers.value = filteredUsers.slice(start, end);
};

/**
 * 处理分页每页显示数量变化
 * @param size 新的每页显示数量
 */
const handleSizeChange = (size) => {
  pageSize.value = size;
  applyFiltersAndPagination();
};

/**
 * 处理分页当前页码变化
 * @param page 新的当前页码
 */
const handleCurrentChange = (page) => {
  currentPage.value = page;
  applyFiltersAndPagination();
};

/**
 * 打开编辑用户弹窗
 * @param user 当前用户数据
 */
const openEditDialog = (user) => {
  editUser.value = { ...user };
  editDialogVisible.value = true;
};

/**
 * 保存编辑后的用户信息
 */
const saveEditUser = async () => {
  try {
    await updateUserInfoApi(editUser.value);
    editDialogVisible.value = false;
    fetchUserList();
  } catch (error) {
    console.error('更新用户信息失败:', error);
  }
};

/**
 * 打开删除用户确认 MessageBox
 * @param id 待删除用户的 ID
 */
const openDeleteConfirm = (id) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await deleteUserByIdApi(id);
        ElMessage.success('用户删除成功');
        fetchUserList();
      } catch (error) {
        ElMessage.error('删除用户失败');
        console.error('删除用户失败:', error);
      }
    })
    .catch(() => {
      // 取消操作
      ElMessage.info('删除操作已取消');
    });
};

/**
 * 更新用户状态
 * @param user 当前用户数据
 */
const updateUserStatus = async (user) => {
  try {
    await updateUserInfoApi(user);
  } catch (error) {
    console.error('更新用户状态失败:', error);
  }
};

// 页面加载时获取用户列表
onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
/* 搜索栏样式 */
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

/* 分页组件样式 */
.pagination {
  margin-top: 10px;
  text-align: right;
}
</style>